const { DataTypes } = require('sequelize');

module.exports = (sequelize) => {
  const PointsTransaction = sequelize.define('PointsTransaction', {
  id: {
    type: DataTypes.BIGINT.UNSIGNED,
    primaryKey: true,
    autoIncrement: true
  },
  userId: {
    type: DataTypes.BIGINT.UNSIGNED,
    allowNull: false,
    field: 'user_id',
    references: {
      model: 'users',
      key: 'id'
    }
  },
  type: {
    type: DataTypes.ENUM('earn', 'consume', 'freeze', 'unfreeze', 'expire', 'transfer_in', 'transfer_out'),
    allowNull: false
  },
  source: {
    type: DataTypes.ENUM('ad_watch', 'invite_register', 'invite_consume', 'invite_recharge', 'recharge_bonus', 'activity', 'admin_adjust', 'transfer', 'consume', 'expire'),
    allowNull: false
  },
  amount: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: false,
    comment: '积分数量'
  },
  balanceBefore: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: false,
    field: 'balance_before',
    comment: '变动前余额'
  },
  balanceAfter: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: false,
    field: 'balance_after',
    comment: '变动后余额'
  },
  relatedId: {
    type: DataTypes.BIGINT.UNSIGNED,
    allowNull: true,
    field: 'related_id',
    comment: '关联ID（订单ID、广告ID等）'
  },
  relatedUserId: {
    type: DataTypes.BIGINT.UNSIGNED,
    allowNull: true,
    field: 'related_user_id',
    comment: '关联用户ID（转账、邀请等）'
  },
  description: {
    type: DataTypes.STRING(255),
    allowNull: true
  },
  expireTime: {
    type: DataTypes.DATE,
    allowNull: true,
    field: 'expire_time',
    comment: '过期时间'
  }
}, {
  tableName: 'point_records',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at'
});

  // 关联关系
  PointsTransaction.associate = (models) => {
    // 与用户的关联
    PointsTransaction.belongsTo(models.User, {
      foreignKey: 'userId',
      as: 'user'
    });
    
    // 与关联用户的关联（用于转账、邀请等）
    PointsTransaction.belongsTo(models.User, {
      foreignKey: 'relatedUserId',
      as: 'relatedUser'
    });
    
    // 与管理员用户的关联（用于管理员调整）
    PointsTransaction.belongsTo(models.User, {
      foreignKey: 'relatedUserId',
      as: 'adminUser'
    });
  };

  return PointsTransaction;
};